//
//  XML_Bloomberg_Search.m
//  MacStockApp
//
//  Created by 英傑 翁 on 12/2/27.
//  Copyright (c) 2012年 翁英傑. All rights reserved.
//

#import "XML_Bloomberg_Search.h"
#import "GBall.h"

@implementation XML_Bloomberg_Search
- (id)init_identify:(NSString *)ident {
	
    if(self=[super init])
	{
        
        identify=ident;
        
        
    }
	
	return self;
}

-(void)dealloc{
    
    
    [super dealloc];
}



-(NSMutableArray *)get_search_array_data:(NSString *)serachstrings count:(int)count {
    
    //最終要將資料傳出的的陣列
    NSMutableArray *outarray=[[[NSMutableArray alloc] init] autorelease];
    
    //使用json分解技巧 
    //先將字串進行jsonvalue取出資料結構：ＥＸ：[caa JSONValue]  
    //如果要取得 {"symbol":"2330.tw","name":"TSMC" } 裡面這些資料是使用NSDictionary 來取得    
    //如果是 [{...},{...}] 表示是陣列 要用NSMutableArray
    
    
    //1.下載網址
    NSString *urls_bloomberg=[NSString stringWithFormat: @"http://m.bloomberg.com/iphone/apps/wds/SymbolSearch.asp?Query=%@&From=1&Count=%i&bbipver=1.0.9,%@,iPad,iPhone%%20OS,5.0.1,zh_TW,zh-Hant",serachstrings,count,identify] ; 
    //
    
    //特別注意 在bloomberg網址中有一段 'iPad,iPhone%20OS,5.0.1,zh_TW,zh-Hant' 因為其中有一個%，因為是使用stringWithFormat
    //所以必須要變成‘a43fa,iPad,iPhone%%20OS,5.0.’ 在此處要兩個 ％％
    
    
    NSURL *  urla_bloomberg;
    urla_bloomberg = [NSURL URLWithString:urls_bloomberg];
    
    NSURL* url =urla_bloomberg;
   
   
    
    NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]
                                    autorelease];
    
    
    [request setValue:Bloomberg_User_Agent forHTTPHeaderField:@"User-Agent"];
    [request setValue:Bloomberg_Pragma forHTTPHeaderField:@"Pragma"]; 
  
    //以下可以欺騙yahoo
    //[request setValue:@"vendor=\"fff\";" forHTTPHeaderField:@"X-Client-Info"];    
    
    NSURLResponse* response = nil;
    NSError* error = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];    
    /*
    
    
    NSError * errorq_bloomberg = nil;
    NSString * download_string_bloomberg;
    
    //2.取出下載文字資料
    download_string_bloomberg=[NSString stringWithContentsOfURL:urla_bloomberg encoding: NSUTF8StringEncoding error:&errorq_bloomberg];    
    
    //3.將文字資料轉成NSData資料
    NSData *data=[NSData dataWithBytes:[download_string_bloomberg UTF8String] length:[download_string_bloomberg length]];
    */
    
    
    
    //4.實體要下載資料的陣列 
    bloomberg_data_array=[[[NSMutableArray alloc] init] autorelease];
    
    //5.建立 data資料解析的分解器
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; //设置XML数据
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];
    //6.委託 記得要<NSXMLParserDelegate>
    [parser setDelegate:self];
    [parser parse];
    
    //7.資料取出之後要做的事情 將bloomberg_data_array 轉成可以比較容易懂取得資料的陣列
	NSLog(@"end Of parseXMLFile");    
    for (NSMutableDictionary *node in bloomberg_data_array) {
        //NSLog(@"==================");
        //NSLog(@"px:WBTKR=%@",[node objectForKey:@"px:WBTKR"]);//代碼
        //NSLog(@"px:DS520=%@",[node objectForKey:@"px:DS520"]);//名稱
        //NSLog(@"px:DS290=%@",[node objectForKey:@"px:DS290"]);//國家        
        //NSLog(@"px:DS213=%@",[node objectForKey:@"px:DS213"]);//證券種類  
        //NSLog(@"px:DS202=%@",[node objectForKey:@"px:DS202"]);//產業分類         
        
        NSMutableDictionary *temdic=[[[NSMutableDictionary alloc] init] autorelease];
         
        NSString *code_s;         //全名
        NSString *symbol_s;       //代碼
        NSString *country_s;      //交易所代碼  
        NSString *name_s;         //名稱
        NSString *typeDisp_s;     //標的種類
        NSString *exchDisp_s;     //交易所名稱
        NSString *class_s; //yahoo 資料不提供證券產業類別        
        
               
        
        if ([node objectForKey:@"px:WBTKR"]!=nil) {
            
                
            code_s=[node objectForKey:@"px:WBTKR"];            
            
            //2.將字串分割
            NSArray * Timestamp_array=[[node objectForKey:@"px:WBTKR"]  componentsSeparatedByString:@":"]; 
            if ([Timestamp_array count]>1) {
                 
                 symbol_s=[Timestamp_array objectAtIndex:0] ;
                 country_s=[Timestamp_array objectAtIndex:1];
            }
            else {
                symbol_s=@"na" ;
                country_s=@"na";
            }
            
        }
        else {
            code_s=@"" ;           
            symbol_s=@"na" ;
            country_s=@"na";                       
        }  
        
        if ([node objectForKey:@"px:DS290"]!=nil) {
            
            exchDisp_s=[node objectForKey:@"px:DS290"];                       
        }
        else {
             
            exchDisp_s=@"";
               
                         
            
        }               
        
        
        if ([node objectForKey:@"px:DS520"]!=nil) {
            
            name_s=[node objectForKey:@"px:DS520"];
        }
        else {
             
            name_s =@"";
        }           
        
        
        //產業分類
        if ([node objectForKey:@"px:DS202"]!=nil) {
           
            class_s=[node objectForKey:@"px:DS202"];
        }
        else {
            class_s=@"";
        } 
        
        //證券種類
        if ([node objectForKey:@"px:DS213"]!=nil) {
            
            typeDisp_s=[node objectForKey:@"px:DS213"] ;
        }
        else {
            typeDisp_s=@"";
        }              
        
        [outarray addObject:temdic];     
        
        [temdic setObject:code_s forKey:@"code"];
        [temdic setObject:symbol_s forKey:@"symbol"];
        [temdic setObject:country_s forKey:@"country"];        
        [temdic setObject:name_s forKey:@"name"];
        [temdic setObject:typeDisp_s forKey:@"typeDisp"];
        [temdic setObject:exchDisp_s forKey:@"exchDisp"];        
        [temdic setObject:class_s forKey:@"class"];               
        
    }
    
    [parser release];
    
    
    
    return outarray;

}
#pragma mark -
#pragma mark 解析xml

/* 如何解析xml資料說明
 
 1.以下是從網路上下載的xml 文件
 http://m.bloomberg.com/iphone/apps/wds/SymbolSearch.asp?Query=2330&From=1&Count=20&bbipver=1.0.9,17243a4e72c7eadd0e9823cd887f97212efa43fa,iPad,iPhone%20OS,5.0.1,zh_TW,zh-Hant
 2012-02-26 18:19:16.817 CodeSign_MacStockApp[10560:ad03] bloomberg=<?xml version="1.0" encoding="ISO-8859-1" ?>
 <px:MarketData xmlns:px="http://www.bloomberg.com/bloomberg-web-pricing" systime="1330251555989" >
 <px:SymbolSearch AllTotalMembers="294179" Count="4" From="1" Query="2330" TotalMembers="4">
 <px:Security>
 <px:WBTKR>2330:TT</px:WBTKR>
 <px:DS520>Taiwan Semiconductor Manufacturing Co Ltd</px:DS520>
 <px:DS290>Taiwan</px:DS290>
 <px:DS213>Common Stock</px:DS213>
 <px:DS202>Semicon Compo-Intg Circu</px:DS202>
 </px:Security>
 <px:Security>
 <px:WBTKR>2330:HK</px:WBTKR>
 <px:DS520>China Uptown Group Co Ltd</px:DS520>
 <px:DS290>Hong Kong</px:DS290>
 <px:DS213>Common Stock</px:DS213>
 <px:DS202>Computers-Integrated Sys</px:DS202>
 </px:Security>
 <px:Security>
 <px:WBTKR>2330:JP</px:WBTKR>
 <px:DS520>SmartEbook.com Co Ltd</px:DS520>
 <px:DS290>Japan</px:DS290>
 <px:DS213>Common Stock</px:DS213>
 <px:DS202>Internet Content-Entmnt</px:DS202>
 </px:Security>
 <px:Security>
 <px:WBTKR>FTDOLX:US</px:WBTKR>
 <px:DS520>First Trust 2330 - Weak Dollar Plus Portfolio - Series 2</px:DS520>
 <px:DS290>USA</px:DS290>
 <px:DS213>UIT</px:DS213>
 <px:DS202></px:DS202>
 </px:Security>
 </px:SymbolSearch>
 
 原始文字資料解釋：
 請注意上面的分類中 通用格式如下：<標記>內容資料</標記> 
 也就是這樣看：先看哪個標記開始，再取出內容資料，最後找到標記結束
 
 2.xml分解所需要的原始文字資料
 
 
 
 3.建立委託
 
 4.委託方法
 
 */


//以下三個method為我們最常使用的NSXMLParserDelegate method


//1. 於遇到XML tag開頭時被呼叫，可取得tag的名稱以及tag裡的attribute

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
	//NSLog(@"Did start element");
	
    if ( [elementName isEqualToString:@"px:Security"]) {
       // NSLog(@"found px:Security");
        //節點開始
        bloomberg_node=[[NSMutableDictionary alloc] init];
        node_name=@"";
        return;
    }
    if ( [elementName isEqualToString:@"px:WBTKR"] ) {
		//NSLog(@"found px:WBTKR");
        node_name=@"px:WBTKR";
        return;
    }
	if ( [elementName isEqualToString:@"px:DS520"] ) {
		//NSLog(@"found px:DS520");
        node_name=@"px:DS520";
        return;
    }
	if ( [elementName isEqualToString:@"px:DS290"] ) {
		//NSLog(@"found px:DS290");
        node_name=@"px:DS290";        
        return;
    }
	if ( [elementName isEqualToString:@"px:DS213"] ) {
		//NSLog(@"found px:DS213");
        node_name=@"px:DS213";
        
        return;
    }    
    if ( [elementName isEqualToString:@"px:DS202"] ) {
		//NSLog(@"found px:DS202");
        node_name=@"px:DS202";        
        return;
    }       
}

//2. 找到XML tag所包含的內容
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    //NSLog(@"foundCharacters %@", string);
    if ([string retainCount]>0) {
        node_value=[string retain];
    }
    else {
        node_value=@"";
    }
    
}


//3. 於遇到XML tag結尾時被呼叫

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    //NSLog(@"didEndElement");
    if ( [elementName isEqualToString:@"px:Security"]) {
        //NSLog(@"end found px:Security");
        //節點結束
        [bloomberg_data_array addObject:bloomberg_node];
        [bloomberg_node release];
        return;
    }
    if ( [elementName isEqualToString:@"px:WBTKR"] ) {
		//NSLog(@"end found px:WBTKR");
        [bloomberg_node setObject: node_value forKey:node_name];
        
        return;
    }
	if ( [elementName isEqualToString:@"px:DS520"] ) {
        
        [bloomberg_node setObject:node_value forKey:node_name];        
        return;
    }
	if ( [elementName isEqualToString:@"px:DS290"] ) {
		//NSLog(@"end found px:DS290");
        [bloomberg_node setObject:node_value forKey:node_name];        
        return;
    }
	if ( [elementName isEqualToString:@"px:DS213"] ) {
		//NSLog(@"end found px:DS213");
        [bloomberg_node setObject:node_value forKey:node_name];        
        return;
    }    
    if ( [elementName isEqualToString:@"px:DS202"] ) {
		//NSLog(@"end found px:DS202");
        [bloomberg_node setObject:node_value forKey:node_name];        
        return;
    }           
}

@end
